<?php
/**
 * Created by PhpStorm.
 * User: buddha
 * Date: 2021/6/18
 * Time: 15:01
 */

namespace app\utils;


use Firebase\JWT\JWT;
use think\facade\Config;

class Token
{
    /**
     * 获取token
     * @param $userInfo
     * @return string
     */
    public static function getToken($userInfo) {
        $token = Config::get('token');
        $key = array_pop($token);
        $token['data'] = $userInfo;
        return JWT::encode($token, $key);
    }

    /**
     * 校验token
     * @param $token
     * @return array
     */
    public static function checkToken($token)
    {
        $key = Config::get('token.key');  // key要和签发的时候一样
        try {
            JWT::$leeway = 60;  // 当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, $key, ['HS256']);  // HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            return $arr;
        }catch(\Exception $e) {  // 其他错误
            return [];
        }
    }
}
